package com.yonyou.ucf.mdf.app.controller.isv;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdf.app.service.impl.ISVAuthService;
import com.yonyoucloud.iuap.ucf.mdd.starter.token.service.TokenService;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.OpenApiProperties;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequest;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequestBody;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.module.auth.tenant.TenantAuthProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;

/**
 * 本类主要用于
 *
 * @author liuhaoi
 * @since Created At 2020/6/2 1:52 下午
 */
@Slf4j
@RestController
@RequestMapping(AuthController.PATH_AUTH_PREFIX)
@RequiredArgsConstructor
public class AuthController {

    public static final String PATH_AUTH_PREFIX = "/rest/v1/abpaas/isv/auth";

    private final TenantAuthProvider tenantAuthProvider;
    private final TokenService tokenService;
    private final ApplicationContext applicationContext;

    private final OpenApiProperties openApiProperties;

    @Value("${yonbuilder_pro_be_host}")
    private String proBeHost;

    private static final String APP_KEY_API = "/openapi/isvappkey";

    private final ISVAuthService isvAuthService;

    private final ISVRequest isvRequest;

    @GetMapping(value = "/code", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void authByUnifyCode(
            @RequestParam String code, HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            log.info("code接口友互通cookies不存在");
            throw new RuntimeException("友互通token不存在，请重新登录");
        }
        Cookie yhtTokenCookie =
                Arrays.stream(cookies)
                        .filter(cookie -> "yht_access_token".equals(cookie.getName()))
                        .findAny()
                        .orElse(null);
        if (yhtTokenCookie == null) {
            log.info("code接口友互通token不存在");
            throw new RuntimeException("友互通token不存在，请重新登录");
        }
        log.info("/code接口友互通token" + yhtTokenCookie.getValue());
    }

    private void getAppKey() {
        String url = proBeHost + APP_KEY_API;
        ISVRequestBody isvRequestBody = new ISVRequestBody();
        isvRequestBody.setUrl(url);
        isvRequestBody.setRequestMethod("GET");
        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("domain", AppContext.getAppConfig().getProperty("spring.application.name"));
        requestMap.put("evnString", AppContext.getAppConfig().getProperty("spring.profiles.active"));
        isvRequestBody.setParams(requestMap);
        String data = isvRequest.doRequest(null, isvRequestBody);
        JSONObject jsonObject = JSON.parseObject(data);
        if (jsonObject != null) {
            JSONObject detailMsg = (JSONObject) jsonObject.get("detailMsg");
            if (detailMsg != null) {
                JSONObject dataJson = (JSONObject) detailMsg.get("data");
                if (dataJson != null) {
                    String domain = dataJson.getString("domainCode");
                    String appCode = dataJson.getString("appCode");
                    String appKey = dataJson.getString("appKey");
                    String appSecret = dataJson.getString("appSecret");
                    Properties appConfig = AppContext.getAppConfig();
                    if (StringUtils.isNotBlank(domain)
                            && domain.equals(appConfig.getProperty("spring.application.name"))) {
                        openApiProperties.setIsvAppCode(appCode);
                        openApiProperties.setIsvAesKey(appKey);
                        openApiProperties.setIsvAppSecret(appSecret);
                        openApiProperties.setIsvAppKey(appKey);
                    } else {
                        throw new RuntimeException("当前租户没有生态appKey");
                    }
                }
            }
        } else {
            throw new RuntimeException("当前租户没有生态appKey");
        }
    }
}
